#!/usr/bin/perl

use strict;

use EP::Config;

my $goUrl = "http://www.geneontology.org";
#my $goOntologyUrl = "$goUrl/ontology";

die "Directory for go files does not exits yet: $EP::Config::h->{EPNG_GODATA_PATH}" if ! -d $EP::Config::h->{EPNG_GODATA_PATH};


# gene ontology files
my @files =  ( "$goUrl/ontology/function.ontology", "$goUrl/ontology/process.ontology", "$goUrl/ontology/component.ontology" );

# species specific files
foreach my $species ( keys %{ $EP::Config::h->{SPECIES_METADATA} } ) {
  if ( exists( $EP::Config::h->{SPECIES_METADATA}->{$species}->{annotationFile} ) ) {
    if ( exists ( $EP::Config::h->{SPECIES_METADATA}->{$species}->{annotationFileURL} ) ) {
      push @files, $EP::Config::h->{SPECIES_METADATA}->{$species}->{annotationFileURL};
    } else {
      push @files, "$goUrl/cgi-bin/GO/downloadGOGA.pl/" . $EP::Config::h->{SPECIES_METADATA}->{$species}->{annotationFile} . ".gz";
    }
  }
}

# download all files
foreach my $file ( @files ) {
    my ($SavedFile) = $file =~ /([^\/]+)$/; # get rid of directory
    my $cmd = "rm $EP::Config::h->{EPNG_GODATA_PATH}/$SavedFile; wget -nv -P $EP::Config::h->{EPNG_GODATA_PATH} $file";
    print $cmd, "\n";
    system( $cmd );

    print STDERR "File not downloaded properly $file\n" if -z "$EP::Config::h->{EPNG_GODATA_PATH}/$SavedFile";

    #unzip the file if necessary
    system("gunzip -f $EP::Config::h->{EPNG_GODATA_PATH}/$SavedFile") if $SavedFile =~/\.gz$/;
}
